//
//  VideoGeneratingVC.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/21.
//

import UIKit
import SVGAPlayer
import Photos
import AVKit

class VideoGeneratingVC: BaseViewController {
    var model:VideoHistoryModel?
    var homeModel:CommunityModel?
    let viewModel = CommunityViewModel()
    let disposeBag = DisposeBag()
    var ids:String?
    var checkTimes: Int = 0
    var isGenerating: Bool = false
    var lastRequestTime: TimeInterval = 0
    private lazy var backView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#25262B")
        view.allRound(4)
        return view
    }()
    
    private lazy var coverIV: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var playBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_home_videoplayer")
      return button
  }()
    
    // 懒加载 SVGAPlayer
    private lazy var svgaPlayer: SVGAPlayer = {
        let player = SVGAPlayer()
        player.translatesAutoresizingMaskIntoConstraints = false
        player.loops = 0  // 设置为无限循环
        player.clearsAfterStop = true
        return player
    }()
    
    private lazy var svgaParser: SVGAParser = {
        return SVGAParser()
    }()
    
    private lazy var scLb: UILabel = {
        let label = UILabel()
        label.text = "正在生成中，可能需要等待 3-15 分钟，您可以稍后在历史中查看。"
        label.textAlignment = .center
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 14)
        label.numberOfLines = 2
        return label
    }()
    
    private lazy var tipsLb: UILabel = {
        let label = UILabel()
        label.text = "视频只保留30天，请及时保存到相册"
        label.textAlignment = .center
        label.textColor = Theme.color.text_d3
        label.font = UIFont.pingFangSCRegular(ofSize: 14)
        label.isHidden = true
        return label
    }()
    
    private lazy var descGenerateBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "保存到相册"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.titleColorForNormal = .white
        button.allRound(24)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.isHidden = true
        return button
    }()
    
    private lazy var likeBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleColorForNormal = Theme.color.text_d1
        button.normalImage = UIImage(named: "icon_com_likeNor")
        button.selectedImage = UIImage(named: "icon_com_likeSel")
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#DFE1E8")
        button.allRound(24)
//        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: <#T##CGFloat#>, bottom: <#T##CGFloat#>, right: <#T##CGFloat#>)
        button.layoutButtonWithEdgeInsetsStyle(.Left, space: 8)
        return button
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.editNav(isCurrent: true)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.editNav(isCurrent: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.removeSubViewController_k(vcName: "VideoStyleViewController")
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        self.navigationItem.title = "正在生成"
        self.view.addSubview(backView)
        backView.addSubview(svgaPlayer)
        backView.addSubview(scLb)
        backView.addSubview(coverIV)
        backView.addSubview(playBtn)
        self.view.addSubview(tipsLb)
        self.view.addSubview(descGenerateBtn)
        
        backView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop).offset(22)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(GET_WIDTH(W: 478))
        }
        
        coverIV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        playBtn.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(coverIV)
        }
        
        tipsLb.snp.makeConstraints { make in
            make.top.equalTo(backView.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview()
        }
        
        if self.homeModel != nil {
            self.view.addSubview(likeBtn)
            likeBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                  make.leading.equalTo(descGenerateBtn.snp.trailing).offset(10)
                  make.trailing.equalToSuperview().offset(-15)
                  make.height.equalTo(48)
            }

            descGenerateBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                make.leading.equalToSuperview().offset(15)
                make.height.equalTo(48)
                make.width.equalTo(likeBtn.snp.width)    
            }
            
            likeBtn.titleForNormal = self.homeModel?.like_count?.formatted
            likeBtn.isSelected = self.homeModel?.is_like == 1 ? true : false
            
            likeBtn.setClosureTouchUpInside_k { [weak self] in
                if let model = self?.homeModel {
                    self?.viewModel.clickLike(model: model)
                }
            }
            self.viewModel.likeSubject.subscribe(onNext: { [weak self] type in
                if type == 0 {
                    self?.homeModel?.like_count! -= 1
                }else {
                    self?.homeModel?.like_count! += 1
                }
                self?.likeBtn.isSelected = type == 1 ? true : false
                self?.homeModel?.is_like = type
                self?.likeBtn.titleForNormal = self?.homeModel?.like_count?.formatted
            }).disposed(by: disposeBag)
        }else {
            descGenerateBtn.snp.makeConstraints { make in
                make.bottom.equalTo(self.safeBottom).offset(-10)
                make.leading.trailing.equalToSuperview().inset(16)
                make.height.equalTo(48)
            }
        }
        
        svgaPlayer.snp.makeConstraints { make in
            make.centerY.equalToSuperview().offset(-30)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(200)
        }
        
        scLb.snp.makeConstraints { make in
            make.top.equalTo(svgaPlayer.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview().inset(24)
        }
        
        loadLocalSVGA(named: "draw_loading")
        if let model = self.homeModel {
            self.navigationItem.title = "视频详情"
            self.coverIV.sd_setImage(with: URL(string: model.img_url))
            self.descGenerateBtn.isHidden = false
            self.tipsLb.isHidden = false
            self.svgaPlayer.stopAnimation()
            self.svgaPlayer.isHidden = true
            self.scLb.isHidden = true
        }else {
            self.getVideoData()
        }
        
        
        descGenerateBtn.setClosureTouchUpInside_k { [weak self] in
            if let model = self?.homeModel, let url = URL(string: model.play_url) {
                self?.saveVideoToAlbum(from: url)
            }
            if let model = self?.model, let url = URL(string: model.video_url) {
                self?.saveVideoToAlbum(from: url)
            }
        }
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "icon_video_hBlack"), for: .normal)
        let leftItem = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.rightBarButtonItem = leftItem
        leftBtn.setClosureTouchUpInside_k { [weak self] in
            if !Appearance.shared.isLoign {
                GlobalRx.loginSubject.onNext(())
                return
            }
            let vc = VideoHistoryViewController()
            self?.navigationController?.pushViewController(vc)
        }
        RequestService.instance.getUserInfo()
        playBtn.setClosureTouchUpInside_k { [weak self] in
            if let model = self?.homeModel, let url = URL(string: model.play_url) {
                NDProgressHUD.showLoading()
                self?.playVideo(from: url)
            }
            if let url = URL(string: self?.model?.video_url ?? "") {
                NDProgressHUD.showLoading()
                self?.playVideo(from: url)
            }
        }
    }
    
    private func loadLocalSVGA(named: String) {
        if let filePath = Bundle.main.path(forResource: named, ofType: "svga") {
            svgaParser.parse(with: URL(fileURLWithPath: filePath), completionBlock: { [weak self] videoItem in
                self?.svgaPlayer.videoItem = videoItem
                self?.svgaPlayer.startAnimation()
            }, failureBlock: { error in
                print("加载 SVGA 文件失败: \(error?.localizedDescription ?? "")")
            })
        } else {
            print("未找到名为 \(named) 的 SVGA 文件")
        }
    }
    
    @objc func getVideoData(){
        guard let checkId = ids, checkId.count > 0 else { return }
        let timestamp = Date().timeIntervalSince1970
        if checkTimes > 60 {
            isGenerating = false
            XLog.d("", "视频超时")
            // stopTimer() // 如果需要停止定时器，请确保实现这个方法
            return
        }
        lastRequestTime = timestamp
        checkTimes += 1
        DispatchQueue.global(qos: .default).async { [weak self] in
            guard let self = self else { return }
            RequestService.instance.getCheckVdieo(checkId: checkId) { model in
                if let model = model {
                    self.model = model
                    if let imageUrl = model.cover_url, imageUrl.count > 0, model.sts == 2 {
                        self.done(imageUrl: imageUrl)
                    }else if model.sts == 3 {
                        //失败
                    }else {
                        self.perform(#selector(self.getVideoData), with: nil, afterDelay: 26)
                    }
                }else { // 其他
                    self.perform(#selector(self.getVideoData), with: nil, afterDelay: 26)
                }
                XLog.d("图像", "完成第\(self.checkTimes)次轮询结果")
            } failureClosure: { error in
                //这里是网络异常
                XLog.d("", error)
            }
        }
    }
    
    
    func done(imageUrl:String){
        guard let model = self.model else { return }
        self.navigationItem.title = "视频详情"
        self.coverIV.sd_setImage(with: URL(string: imageUrl))
        self.descGenerateBtn.isHidden = false
        self.tipsLb.isHidden = false
        self.svgaPlayer.stopAnimation()
        self.svgaPlayer.isHidden = true
        self.scLb.isHidden = true
    }
    
    
    func saveVideoToAlbum(from url: URL) {
        // 显示加载进度
        NDProgressHUD.showLoading()
        // 使用 URLSession 下载视频
        let session = URLSession(configuration: .default)
        let downloadTask = session.downloadTask(with: url) { location, response, error in
            guard let location = location, error == nil else {
                // 下载失败
                NDProgressHUD.showError(title: "", subtitle: "Download failed: \(error?.localizedDescription ?? "Unknown error")")
                return
            }
            do {
                // 获取临时文件路径
                let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
                let tempFileURL = tempDirectoryURL.appendingPathComponent(url.lastPathComponent)
                // 移动文件到临时路径
                try FileManager.default.moveItem(at: location, to: tempFileURL)
                // 请求相册权限
                PHPhotoLibrary.requestAuthorization { status in
                    if status == .authorized {
                        NDProgressHUD.showLoading()
                        // 保存视频到相册
                        PHPhotoLibrary.shared().performChanges({
                            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: tempFileURL)
                        }) { success, error in
                            DispatchQueue.main.async {
                                if success {
                                    NDProgressHUD.showSuccess(title: "", subtitle: "视频保存成功!")
                                } else {
                                    NDProgressHUD.showError(title: "", subtitle: "Save failed: \(error?.localizedDescription ?? "Unknown error")")
                                }
                                // 删除临时文件
                                try? FileManager.default.removeItem(at: tempFileURL)
                            }
                        }
                    } else {
                        NDProgressHUD.showError(title: "", subtitle: "没有相册权限")
                    }
                }
            } catch {
                NDProgressHUD.showError(title: "", subtitle: "File handling failed: \(error.localizedDescription)")
            }
        }
        downloadTask.resume()
    }
    
    func configureAudioSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback, options: [])
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("Failed to set audio session category. Error: \(error)")
        }
    }

    func playVideo(from url: URL) {
        configureAudioSession()
        let player = AVPlayer(url: url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        // 添加观察者以监控视频是否准备好播放
        player.addObserver(self, forKeyPath: "status", options: [.new, .initial], context: nil)
        // Present the AVPlayerViewController
        self.present(playerViewController, animated: true) {
            player.play()
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status" {
            if let player = object as? AVPlayer {
                if player.status == .readyToPlay {
                    // 视频准备好播放，隐藏加载框
                    NDProgressHUD.hide()
                    player.removeObserver(self, forKeyPath: "status")
                } else if player.status == .failed {
                    // 视频加载失败，隐藏加载框并显示错误
                    NDProgressHUD.hide()
                    print("Failed to load video")
                    player.removeObserver(self, forKeyPath: "status")
                }
            }
        }
    }
}
